const mysql = require("mysql");
const config = require("../db/index");

// 连接mysql
function connect() {
  const { host, user, password, database } = config;
  return mysql.createConnection({
    host,
    user,
    password,
    database,
  });
}

// 新建查询连接
function querySql(sql) {
  const conn = connect();
  return new Promise((resolve, reject) => {
    try {
      conn.query(sql, (err, res) => {
        // console.log("sql-err", err);
        // console.log("sql-res", res);

        if (err) {
          reject(err);
        } else {
          resolve(res);
        }
      });
    } catch (e) {
      reject(e);
    } finally {
      // 释放连接
      conn.end();
    }
  });
}
// 查询一条语句
function queryOne(sql) {
  return new Promise((resolve, reject) => {
    querySql(sql)
      .then((res) => {
        console.log("res===", res);
        if (res && res.length > 0) {
          resolve(res[0]);
        } else {
          resolve(null);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}
function camelCaseKeys(obj) {
  const result = {};
  for (let key in obj) {
    let newKey =
      key[0].toLowerCase() +
      key.slice(1).replace(/_([a-z])/g, function ($0, $1) {
        return $1.toUpperCase();
      });
    result[newKey] = obj[key];
  }
  return result;
}

let query = function (sql, values) {
  // 返回一个 Promise
  return new Promise((resolve, reject) => {
    pool.getConnection(function (err, connection) {
      if (err) {
        reject(err);
      } else {
        connection.query(sql, values, (err, rows) => {
          if (err) {
            reject(err);
          } else {
            rows = rows.map((item) => camelCaseKeys(item));
            resolve(rows);
          }
          // 结束会话
          connection.release();
        });
      }
    });
  });
};

module.exports = {
  querySql,
  queryOne,
  query,
};
